package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"news-talk/cache"
	"news-talk/models"
	"strconv"
	"time"
)

func NewsAdd(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	if title == "" || content == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "标题和内容不能为空",
		})
		return
	}
	news := models.News{
		Title:   title,
		Content: content,
		Img:     img,
		UserId:  userId,
	}
	err := models.DB.Create(&news).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "发布失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "发布成功",
			"data": news,
		})
		return
	}
}
func NewsList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var news []models.News
	list_key := "list_page_" + strconv.Itoa(page)
	cachejson, _ := cache.Rdb.Get(cache.Ctx, list_key).Result()
	if cachejson == "" {
		models.DB.Offset(offset).Limit(size).Find(&news)
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &news)
	}
	var total int64
	models.DB.Model(&news).Count(&total)
	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  news,
		"total": total,
	})
	return
}
func NewsDetail(c *gin.Context) {
	id := c.Query("id")
	var news models.News
	detail_key := "detail_" + id
	cachejson, _ := cache.Rdb.Get(cache.Ctx, detail_key).Result()
	if cachejson == "" {
		models.DB.Where("id=?", id).First(&news)
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, detail_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &news)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": news,
	})
	return
}
func Comment(c *gin.Context) {
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	newsId, _ := strconv.Atoi(c.PostForm("news_id"))
	content := c.PostForm("content")
	tx := models.DB.Begin()
	comment := models.Comment{
		Content: content,
		UserId:  userId,
		NewsId:  newsId,
	}
	err := tx.Create(&comment).Error
	if err != nil {
		tx.Rollback()
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "评论失败",
		})
		return
	}
	var news models.News
	err = tx.First(&news, newsId).Error
	if err != nil {
		tx.Rollback()
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "没有找到该新闻",
		})
		return
	}
	news.CommentCount++
	err = tx.Save(&news).Error
	if err != nil {
		tx.Rollback()
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "评论量更新失败",
		})
		return
	} else {
		tx.Commit()
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "评论成功",
			"data": comment,
		})
		return
	}
}
